<?php
namespace App\Admin\Controllers\Order;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Amazon\AmazonOrder;
use App\Models\Amazon\AmazonOrderItem;
use App\Models\Amazon\AmazonOrderItem as OrderItems;
use App\Models\Amazon\AmazonOrderItemOld;
use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysCountry;
use App\Models\Product\ProductAmazonSku;
use App\Util\RExcel;
use Encore\Admin\Admin as SAdmin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;
class AmazonItemController extends AdminController{

    protected $title = '亚马逊订单产品列表';

    protected function _style()
    {
        return <<<STYLE
.column-__actions__ {
    white-space: nowrap;
}
STYLE;
    }

    protected function grid()
    {
        SAdmin::style($this->_style());

        //$orderItem = AmazonOrderItem::query()
        //    ->select('id','amazon_order_id', 'order_item_id', 'account_id', 'sku', 'asin', 'quantity', 'quantity_shipped', 'currency', 'price', 'shipping_price', 'shipping_discount', 'promotion_discount', 'created_at', 'updated_at');
        //$query = AmazonOrderItemOld::query()
        //    ->select('id','amazon_order_id', 'order_item_id', 'account_id', 'sku', 'asin', 'quantity', 'quantity_shipped', 'currency', 'price', 'shipping_price', 'shipping_discount', 'promotion_discount', 'created_at', 'updated_at')
        //    ->union($orderItem);
        //$sql = $query->toSql();
        //
        //$grid = new Grid(new OrderItems());
        //$grid->model()->setTable(DB::raw('('.$sql.') AS T'));

        $grid = new Grid(new AmazonOrderItem());
        $grid->model()->orderBy('id', 'DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->account = SysPlatAccount::getAccountById($item->account_id);
                $countryId = AmazonCountry::getCountryIdByMarketplaceId($item->order->marketplace_id);
                $item->country = SysCountry::getCountryById($countryId);
                $amazonSku = ProductAmazonSku::query()->where(['seller_sku' => $item->sku, 'country_id' => $countryId])->first();
                $item->sku_name = $amazonSku->sku->psku_cn ?? '';
            }
            return $collection;
        });
        $grid->column('id','ID');
        $grid->column('amazon_order_id','订单号');
        $grid->column('account','账号');
        $grid->column('country','国家');
        $grid->column('order.order_status','状态')->using(AmazonOrder::$_orderStatus);
        $grid->column('order.purchase_date','下单时间');
        $grid->column('sku','SKU');
        $grid->column('sku_name','SKU名称');
        $grid->column('asin','ASIN');
        $grid->column('currency','币种');
        $grid->column('price','售价');
        $grid->column('promotion_discount','促销费');
        $grid->column('quantity','数量');
        $grid->column('quantity_shipped','发货数量');
        $grid->fixHeader();
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('order/order-detail-download'));
        });
        $grid->disableActions();
        $grid->disableBatchActions();
        $grid->disableCreateButton();
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter){
                $filter->where(function ($query) {
                    $query->where('sku', 'like', "%{$this->input}%")
                        ->orWhere('asin', 'like', "%{$this->input}%");
                }, '查询','sku8')->placeholder('SKU，ASIN');
                $filter->equal('account_id','账号')->select(SysPlatAccount::options());
                $filter->equal('order.marketplace_id','国家')->select(AmazonCountry::marketplaceOptions());
            });
            $filter->column(1/2, function ($filter){
                $filter->equal('amazon_order_id', '订单号');
                $filter->between('order.purchase_date', '日期')->date();
                $filter->equal('order.order_status','状态')->select(AmazonOrder::$_orderStatus);
            });
        });
        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = AmazonOrderItem::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->where(function ($query) use($_filter){
                    $query->where('sku', 'like', "%{$_filter}%")
                        ->orWhere('asin', 'like', "%{$_filter}%");
                });
            }
            if($key == 'order'){
                $query->whereHas('order', function ($query) use($_filter){
                    foreach ($_filter as $field => $filter){
                        if($field == 'purchase_date'){
                            if(isset($filter['start'])&&$filter['start']){
                                $query->where($field,'>=',$filter['start'] . ' 00:00:00');
                            }
                            if(isset($filter['end'])&&$filter['end']){
                                $query->where($field,'<=',$filter['end'] . ' 23:59:59');
                            }
                        }else{
                            $query->where($field, $filter);
                        }
                    }
                });
            }
            if(in_array($key,['amazon_order_id','account_id'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['订单号','账号','国家','状态','下单时间','SKU','SKU名称','ASIN','币种','售价','促销费','数量','发货数量'];
        RExcel::exportCsv('亚马逊订单产品列表',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res)
    {
        $account = [];
        $country = [];
        foreach ($res as $model){
            if(!array_key_exists($model->account_id,$account)){
                $account[$model->account_id] = SysPlatAccount::getAccountById($model->account_id);
            }
            if(!array_key_exists($model->order->marketplace_id,$country)){
                $countryId = AmazonCountry::getCountryIdByMarketplaceId($model->order->marketplace_id);
                $country[$model->order->marketplace_id] = SysCountry::getCountryById($countryId);
            }

            $amazonSku = ProductAmazonSku::query()->where([
                'seller_sku' => $model->sku,
                'country_id' => $countryId
            ])->first();
            $skuName = $amazonSku->sku->psku_cn ?? '';

            $temp = [
                $model->amazon_order_id,
                $account[$model->account_id],
                $country[$model->order->marketplace_id],
                AmazonOrder::$_orderStatus[$model->order->order_status],
                $model->order->purchase_date ?? '',
                $model->sku,
                $model->sku_name = $skuName,
                $model->asin,
                $model->currency,
                $model->price,
                $model->promotion_discount,
                $model->quantity,
                $model->quantity_shipped,
            ];
            yield $temp;
        }
    }
}
